package com.jorado.apollo.util;

import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.foundation.Foundation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: len.zhang
 * @Date: 2019/4/24 18:09
 * @Description: 自带的与公司的太繁琐，添加此类方便使用
 */
public class ApolloUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApolloUtils.class);

    private static final Map<String, String> META_SERVICES = new HashMap<>();

    static {

        addMetaService("default", "http://p-apollo-configservice.zpidc.com");
        addMetaService("dev", "http://172.17.6.22:8080");
        addMetaService("local", "http://172.17.6.22:8080");
    }

    public static String getMetaService(String env) {
        if (StringUtils.isBlank(env)) {
            return META_SERVICES.get("default");
        }
        String server = META_SERVICES.get(env.toLowerCase());
        if (!StringUtils.isBlank(server)) {
            return server;
        }
        return META_SERVICES.get("default");
    }

    public static void addMetaService(String env, String metaService) {
        META_SERVICES.put(env, metaService);
        LOGGER.info("reg apollo meta service,env:{},service:{}", env, metaService);
    }

    public static String registerEnvInfo(String appId, String env, String cluster) {
        String meta = getMetaService(env);
        System.setProperty("app.id", appId);
        System.setProperty("env", env);
        System.setProperty("apollo.cluster", cluster);
        System.setProperty("apollo.meta", meta);
        printApolloEnvInfo();
        return meta;
    }

    public static String printApolloEnvInfo(String... args) {
        String message = String.format("AppId: %s, Env: %s, DC: %s, IP: %s, Meta:%s", Foundation.app()
                        .getAppId(), Foundation.server().getEnvType(), Foundation.server().getDataCenter(),
                Foundation.net().getHostAddress(), getMetaService(Foundation.server().getEnvType()));

        for (String arg : args) {
            message += ", " + arg;
        }
        LOGGER.info(message);
        return message;
    }
}
